package com.example.sams.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.sams.domain.enums.CourseStatus;
import com.example.sams.domain.po.*;
import com.example.sams.domain.request.ApplyCourseRequest;
import com.example.sams.domain.request.UpdateTeacherProfileRequest;
import com.example.sams.constant.HttpStatus;
import com.example.sams.domain.vo.CourseVO;
import com.example.sams.domain.vo.TimeSlotVO;
import com.example.sams.mapper.AdminsMapper;
import com.example.sams.mapper.CoursesMapper;
import com.example.sams.mapper.StudentsMapper;
import com.example.sams.mapper.TeachersMapper;
import com.example.sams.service.*;
import com.example.sams.domain.enums.CourseReviewsStatus;
import com.example.sams.utils.ResultUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.sams.utils.UuidUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 教师表 服务实现类
 * </p>
 *
 * @author jinghong
 * @since 2025-11-04
 */
@Service
public class TeachersServiceImpl extends ServiceImpl<TeachersMapper, Teachers> implements ITeachersService {

    @Autowired
    private IUsersService usersService;

    @Autowired
    private CoursesMapper coursesMapper;

    @Autowired
    private ITimeSlotsService timeSlotsService;

    @Autowired
    private IEnrollmentsService enrollmentsService;

    @Autowired
    private StudentsMapper studentsMapper;

    @Autowired
    private AdminsMapper adminsMapper;

    @Autowired
    private ICourseReviewsService courseReviewsService;

    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 解析时间字符串，格式：周一 14:00-16:00
     * @param timeStr 时间字符串
     * @return Map包含dayOfWeek, start, end
     */
    private Map<String, Object> parseTimeString(String timeStr) {
        Map<String, Object> result = new HashMap<>();
        
        // 星期映射
        Map<String, Integer> dayMap = new HashMap<>();
        dayMap.put("周一", 1);
        dayMap.put("周二", 2);
        dayMap.put("周三", 3);
        dayMap.put("周四", 4);
        dayMap.put("周五", 5);
        dayMap.put("周六", 6);
        dayMap.put("周日", 7);
        dayMap.put("星期一到", 1);
        dayMap.put("星期二", 2);
        dayMap.put("星期三", 3);
        dayMap.put("星期四", 4);
        dayMap.put("星期五", 5);
        dayMap.put("星期六", 6);
        dayMap.put("星期日", 7);

        // 匹配模式：周X HH:mm-HH:mm
        Pattern pattern = Pattern.compile("(周[一二三四五六日]|星期[一二三四五六日])\\s+(\\d{1,2}):(\\d{2})-(\\d{1,2}):(\\d{2})");
        Matcher matcher = pattern.matcher(timeStr);
        
        if (matcher.find()) {
            String dayStr = matcher.group(1);
            Integer dayOfWeek = dayMap.get(dayStr);
            if (dayOfWeek == null) {
                // 尝试其他格式
                if (dayStr.contains("一")) dayOfWeek = 1;
                else if (dayStr.contains("二")) dayOfWeek = 2;
                else if (dayStr.contains("三")) dayOfWeek = 3;
                else if (dayStr.contains("四")) dayOfWeek = 4;
                else if (dayStr.contains("五")) dayOfWeek = 5;
                else if (dayStr.contains("六")) dayOfWeek = 6;
                else if (dayStr.contains("日")) dayOfWeek = 7;
            }
            
            int startHour = Integer.parseInt(matcher.group(2));
            int startMinute = Integer.parseInt(matcher.group(3));
            int endHour = Integer.parseInt(matcher.group(4));
            int endMinute = Integer.parseInt(matcher.group(5));
            
            result.put("dayOfWeek", dayOfWeek);
            result.put("start", LocalTime.of(startHour, startMinute));
            result.put("end", LocalTime.of(endHour, endMinute));
        } else {
            // 如果解析失败，使用默认值
            result.put("dayOfWeek", 1);
            result.put("start", LocalTime.of(8, 0));
            result.put("end", LocalTime.of(10, 0));
        }
        
        return result;
    }

    @Override
    public ResultUtil getCurrentTeacherInfo(String userId) {
        // 1. 查询用户信息
        Users user = usersService.getById(userId);
        if (user == null) {
            return ResultUtil.error("用户不存在");
        }

        // 2. 查询教师信息
        LambdaQueryWrapper<Teachers> teacherWrapper = new LambdaQueryWrapper<>();
        teacherWrapper.eq(Teachers::getUserId, userId);
        Teachers teacher = this.getOne(teacherWrapper);
        if (teacher == null) {
            return ResultUtil.error("教师信息不存在");
        }

        // 3. 构建返回VO，包含所有可用字段
        Map<String, Object> teacherInfo = new HashMap<>();
        teacherInfo.put("id", teacher.getId());
        teacherInfo.put("name", user.getName());
        teacherInfo.put("account", teacher.getAccount());
        teacherInfo.put("college", user.getCollege());
        teacherInfo.put("title", teacher.getTitle());
        // 添加邮箱和电话字段（可能为null）
        teacherInfo.put("email", user.getEmail());
        teacherInfo.put("phone", user.getPhone());
        // 添加研究方向字段（可能为null）
        teacherInfo.put("researchArea", teacher.getResearchArea());
        // 添加简介字段（可能为null）
        teacherInfo.put("intro", teacher.getIntro());
        // 添加发表论文数字段（数据库中没有，设为null）
        teacherInfo.put("publishedPapers", null);

        return ResultUtil.success(teacherInfo);
    }

    @Override
    @Transactional
    public ResultUtil updateProfile(String userId, UpdateTeacherProfileRequest request) {
        // 1. 验证请求参数
        if (userId == null || userId.trim().isEmpty()) {
            return ResultUtil.error("用户ID不能为空");
        }

        // 2. 查询用户信息
        Users user = usersService.getById(userId);
        if (user == null) {
            return ResultUtil.error("用户不存在");
        }

        // 3. 查询教师信息
        LambdaQueryWrapper<Teachers> teacherWrapper = new LambdaQueryWrapper<>();
        teacherWrapper.eq(Teachers::getUserId, userId);
        Teachers teacher = this.getOne(teacherWrapper);
        if (teacher == null) {
            return ResultUtil.error("教师信息不存在");
        }

        // 4. 更新用户信息（只更新非空字段）
        boolean needUpdateUser = false;
        if (request.getName() != null && !request.getName().trim().isEmpty()) {
            user.setName(request.getName().trim());
            needUpdateUser = true;
        }
        if (request.getCollege() != null && !request.getCollege().trim().isEmpty()) {
            user.setCollege(request.getCollege().trim());
            needUpdateUser = true;
        }

        // 5. 更新教师信息
        boolean needUpdateTeacher = false;
        if (request.getTitle() != null && !request.getTitle().trim().isEmpty()) {
            teacher.setTitle(request.getTitle().trim());
            needUpdateTeacher = true;
        }

        // 6. 执行更新
        if (needUpdateUser) {
            boolean updated = usersService.updateById(user);
            if (!updated) {
                return ResultUtil.error("更新失败，请重试");
            }
        }

        if (needUpdateTeacher) {
            boolean updated = this.updateById(teacher);
            if (!updated) {
                return ResultUtil.error("更新失败，请重试");
            }
        }

        // 7. 如果没有需要更新的字段，返回错误
        if (!needUpdateUser && !needUpdateTeacher) {
            return ResultUtil.error("没有需要更新的字段");
        }

        // 8. 返回更新后的教师信息
        return getCurrentTeacherInfo(userId);
    }

    @Override
    public ResultUtil getAppliedCourses(String userId) {
        // 1. 查询教师信息
        LambdaQueryWrapper<Teachers> teacherWrapper = new LambdaQueryWrapper<>();
        teacherWrapper.eq(Teachers::getUserId, userId);
        Teachers teacher = this.getOne(teacherWrapper);
        if (teacher == null) {
            return ResultUtil.error("教师信息不存在");
        }

        // 2. 查询该教师申请的所有课程
        LambdaQueryWrapper<Courses> courseWrapper = new LambdaQueryWrapper<>();
        courseWrapper.eq(Courses::getTeacherId, teacher.getId());
        courseWrapper.orderByDesc(Courses::getApplyDate);
        List<Courses> courses = coursesMapper.selectList(courseWrapper);

        // 3. 构建返回列表
        List<Map<String, Object>> applicationList = new ArrayList<>();
        for (Courses course : courses) {
            Map<String, Object> application = new HashMap<>();
            application.put("id", course.getId());
            application.put("name", course.getName());
            application.put("time", formatTimeSlots(course.getId())); // 格式化时间段
            application.put("credit", course.getCredit());
            application.put("startWeek", getStartWeek(course.getId()));
            application.put("endWeek", getEndWeek(course.getId()));
            application.put("status", course.getStatus() != null ? course.getStatus().name() : "pending");
            application.put("applyDate", course.getApplyDate() != null ? course.getApplyDate().toString() : null);
            applicationList.add(application);
        }

        return ResultUtil.success(applicationList);
    }

    /**
     * 格式化时间段为字符串，如"周一 14:00-16:00"
     */
    private String formatTimeSlots(String courseId) {
        LambdaQueryWrapper<TimeSlots> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TimeSlots::getCourseId, courseId);
        List<TimeSlots> timeSlots = timeSlotsService.list(wrapper);
        
        if (timeSlots.isEmpty()) {
            return "";
        }
        
        TimeSlots firstSlot = timeSlots.get(0);
        String[] dayNames = {"", "周一", "周二", "周三", "周四", "周五", "周六", "周日"};
        String dayName = firstSlot.getDayOfWeek() != null && firstSlot.getDayOfWeek() >= 1 && firstSlot.getDayOfWeek() <= 7
                ? dayNames[firstSlot.getDayOfWeek()] : "周一";
        
        String start = firstSlot.getStart() != null ? firstSlot.getStart().format(DateTimeFormatter.ofPattern("HH:mm")) : "08:00";
        String end = firstSlot.getEnd() != null ? firstSlot.getEnd().format(DateTimeFormatter.ofPattern("HH:mm")) : "10:00";
        
        return dayName + " " + start + "-" + end;
    }

    /**
     * 获取课程的开始周
     */
    private Integer getStartWeek(String courseId) {
        LambdaQueryWrapper<TimeSlots> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TimeSlots::getCourseId, courseId);
        List<TimeSlots> timeSlots = timeSlotsService.list(wrapper);
        if (!timeSlots.isEmpty() && timeSlots.get(0).getStartWeek() != null) {
            return timeSlots.get(0).getStartWeek();
        }
        return null;
    }

    /**
     * 获取课程的结束周
     */
    private Integer getEndWeek(String courseId) {
        LambdaQueryWrapper<TimeSlots> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TimeSlots::getCourseId, courseId);
        List<TimeSlots> timeSlots = timeSlotsService.list(wrapper);
        if (!timeSlots.isEmpty() && timeSlots.get(0).getEndWeek() != null) {
            return timeSlots.get(0).getEndWeek();
        }
        return null;
    }

    @Override
    @Transactional
    public ResultUtil applyCourse(String userId, ApplyCourseRequest request) {
        // 1. 参数校验
        if (request == null) {
            return ResultUtil.error("请求参数不能为空");
        }
        if (request.getName() == null || request.getName().trim().isEmpty()) {
            return ResultUtil.error("课程名称不能为空");
        }
        if (request.getCredit() == null || request.getCredit() <= 0) {
            return ResultUtil.error("学分必须大于0");
        }
        if (request.getMaxCapacity() == null || request.getMaxCapacity() <= 0) {
            return ResultUtil.error("最大容量必须大于0");
        }
        if (request.getStartWeek() == null || request.getEndWeek() == null) {
            return ResultUtil.error("开始周和结束周不能为空");
        }
        if (request.getStartWeek() > request.getEndWeek()) {
            return ResultUtil.error("开始周不能大于结束周");
        }
        if (request.getTime() == null || request.getTime().trim().isEmpty()) {
            return ResultUtil.error("上课时间不能为空");
        }

        // 2. 查询教师信息
        LambdaQueryWrapper<Teachers> teacherWrapper = new LambdaQueryWrapper<>();
        teacherWrapper.eq(Teachers::getUserId, userId);
        Teachers teacher = this.getOne(teacherWrapper);
        if (teacher == null) {
            return ResultUtil.error("教师信息不存在");
        }

        // 3. 创建课程
        Courses course = new Courses();
        course.setId(UuidUtil.generateCourseId());
        course.setName(request.getName().trim());
        course.setTeacherId(teacher.getId());
        course.setCredit(request.getCredit());
        course.setCapacity(request.getMaxCapacity());
        course.setEnrolledCount(0);
        course.setStatus(CourseStatus.pending);
        course.setApplyDate(LocalDate.now());
        course.setCreatedAt(LocalDateTime.now());
        course.setUpdatedAt(LocalDateTime.now());

        int result = coursesMapper.insert(course);
        if (result <= 0) {
            return ResultUtil.error("课程申请失败");
        }

        // 4. 创建课程审核记录（申请时创建，待管理员审核）
        // 由于表结构要求 reviewer_id 和 status 不能为 NULL，使用第一个管理员作为占位审核人
        // 审核时会更新为实际审核人和正确的审核状态
        LambdaQueryWrapper<Admins> adminWrapper = new LambdaQueryWrapper<>();
        adminWrapper.last("LIMIT 1");
        Admins firstAdmin = adminsMapper.selectOne(adminWrapper);
        
        if (firstAdmin != null) {
            CourseReviews courseReview = new CourseReviews();
            courseReview.setId(UuidUtil.generateCourseReviewId());
            courseReview.setCourseId(course.getId());
            // 使用第一个管理员作为占位审核人，审核时会更新为实际审核人
            courseReview.setReviewerId(firstAdmin.getId());
            // status 暂时设为 rejected（占位值），审核时会更新为正确的值
            // 注意：由于表结构限制，不能设为 NULL，所以使用 rejected 作为占位值
            courseReview.setStatus(CourseReviewsStatus.rejected); // 占位值，审核时会更新
            courseReview.setReason("待审核"); // 申请时的占位原因
            courseReview.setReviewedAt(LocalDateTime.now()); // 申请时间
            
            try {
                courseReviewsService.save(courseReview);
            } catch (Exception e) {
                // 如果创建审核记录失败，回滚课程创建
                return ResultUtil.error("创建课程审核记录失败: " + e.getMessage());
            }
        } else {
            // 如果没有管理员，无法创建审核记录，返回错误
            return ResultUtil.error("系统中没有管理员，无法创建课程审核记录");
        }

        // 5. 解析时间字符串并创建时间段（支持多个时间段，用逗号分隔）
        if (request.getTime() != null && !request.getTime().trim().isEmpty()) {
            String timeStr = request.getTime().trim();
            
            // 按中文逗号或英文逗号分割时间段
            String[] timeSlots = timeStr.split("[，,]");
            Pattern timePattern = Pattern.compile("(周[一二三四五六日]|星期[一二三四五六日])\\s+(\\d{1,2}):(\\d{2})-(\\d{1,2}):(\\d{2})");
            
            // 生成weeks数组（所有时间段共用）
            List<Integer> weeks = new ArrayList<>();
            for (int i = request.getStartWeek(); i <= request.getEndWeek(); i++) {
                weeks.add(i);
            }
            String weeksJson;
            try {
                weeksJson = objectMapper.writeValueAsString(weeks);
            } catch (Exception e) {
                weeksJson = "[]";
            }
            
            // 解析每个时间段并创建TimeSlot记录
            for (String singleTimeStr : timeSlots) {
                singleTimeStr = singleTimeStr.trim();
                if (singleTimeStr.isEmpty()) {
                    continue;
                }
                
                // 验证时间格式
                if (!timePattern.matcher(singleTimeStr).find()) {
                    return ResultUtil.error("时间格式不正确，请使用格式：周一 14:00-16:00");
                }
                
                Map<String, Object> timeInfo = parseTimeString(singleTimeStr);
                Integer dayOfWeek = (Integer) timeInfo.get("dayOfWeek");
                LocalTime start = (LocalTime) timeInfo.get("start");
                LocalTime end = (LocalTime) timeInfo.get("end");
                
                // 验证时间合理性
                if (start != null && end != null && !start.isBefore(end)) {
                    return ResultUtil.error("开始时间必须早于结束时间");
                }

                TimeSlots timeSlot = new TimeSlots();
                timeSlot.setId(UuidUtil.generateTimeSlotId());
                timeSlot.setCourseId(course.getId());
                timeSlot.setDayOfWeek(dayOfWeek);
                timeSlot.setStart(start);
                timeSlot.setEnd(end);
                timeSlot.setRoom("待分配"); // 默认教室
                timeSlot.setStartWeek(request.getStartWeek());
                timeSlot.setEndWeek(request.getEndWeek());
                timeSlot.setWeeks(weeksJson);

                timeSlotsService.save(timeSlot);
            }
        }

        // 6. 构建返回数据
        Map<String, Object> resultData = new HashMap<>();
        resultData.put("id", course.getId());
        resultData.put("name", course.getName());
        resultData.put("status", course.getStatus().name());

        return ResultUtil.success("申请提交成功", resultData);
    }

    @Override
    @Transactional
    public ResultUtil cancelApplication(String userId, String applicationId) {
        // 1. 参数校验
        if (applicationId == null || applicationId.trim().isEmpty()) {
            return ResultUtil.error("申请ID不能为空");
        }

        // 2. 查询教师信息
        LambdaQueryWrapper<Teachers> teacherWrapper = new LambdaQueryWrapper<>();
        teacherWrapper.eq(Teachers::getUserId, userId);
        Teachers teacher = this.getOne(teacherWrapper);
        if (teacher == null) {
            return ResultUtil.error("教师信息不存在");
        }

        // 3. 查询课程
        Courses course = coursesMapper.selectById(applicationId);
        if (course == null) {
            return ResultUtil.error(HttpStatus.NOT_FOUND, "申请不存在");
        }

        // 4. 验证课程是否属于该教师
        if (!course.getTeacherId().equals(teacher.getId())) {
            return ResultUtil.error("无权操作该申请");
        }

        // 5. 验证课程状态
        if (course.getStatus() == CourseStatus.approved) {
            return ResultUtil.error("课程已审核通过，无法取消");
        }

        // 6. 删除时间段
        LambdaQueryWrapper<TimeSlots> timeSlotWrapper = new LambdaQueryWrapper<>();
        timeSlotWrapper.eq(TimeSlots::getCourseId, applicationId);
        timeSlotsService.remove(timeSlotWrapper);

        // 7. 删除课程
        int result = coursesMapper.deleteById(applicationId);
        if (result <= 0) {
            return ResultUtil.error("取消失败");
        }

        return ResultUtil.success("申请已取消");
    }

    @Override
    public ResultUtil getMyCourses(String userId) {
        // 1. 查询教师信息
        LambdaQueryWrapper<Teachers> teacherWrapper = new LambdaQueryWrapper<>();
        teacherWrapper.eq(Teachers::getUserId, userId);
        Teachers teacher = this.getOne(teacherWrapper);
        if (teacher == null) {
            return ResultUtil.error("教师信息不存在");
        }

        // 2. 查询该教师已审核通过的课程
        LambdaQueryWrapper<Courses> courseWrapper = new LambdaQueryWrapper<>();
        courseWrapper.eq(Courses::getTeacherId, teacher.getId());
        courseWrapper.eq(Courses::getStatus, CourseStatus.approved);
        List<Courses> courses = coursesMapper.selectList(courseWrapper);

        // 3. 查询用户信息（用于获取教师姓名）
        Users user = usersService.getById(userId);

        // 4. 构建课程列表
        List<CourseVO> courseVOList = new ArrayList<>();
        for (Courses course : courses) {
            // 查询时间段信息
            List<TimeSlotVO> timeSlotVOList = new ArrayList<>();
            LambdaQueryWrapper<TimeSlots> timeSlotWrapper = new LambdaQueryWrapper<>();
            timeSlotWrapper.eq(TimeSlots::getCourseId, course.getId());
            List<TimeSlots> timeSlots = timeSlotsService.list(timeSlotWrapper);

            for (TimeSlots timeSlot : timeSlots) {
                TimeSlotVO timeSlotVO = TimeSlotVO.builder()
                        .dayOfWeek(timeSlot.getDayOfWeek())
                        .start(timeSlot.getStart() != null ? timeSlot.getStart().format(DateTimeFormatter.ofPattern("HH:mm")) : null)
                        .end(timeSlot.getEnd() != null ? timeSlot.getEnd().format(DateTimeFormatter.ofPattern("HH:mm")) : null)
                        .room(timeSlot.getRoom())
                        .startWeek(timeSlot.getStartWeek())
                        .endWeek(timeSlot.getEndWeek())
                        .build();

                // 解析weeks JSON字符串为List<Integer>
                if (timeSlot.getWeeks() != null && !timeSlot.getWeeks().isEmpty()) {
                    try {
                        List<Integer> weeks = objectMapper.readValue(timeSlot.getWeeks(), new TypeReference<List<Integer>>() {});
                        timeSlotVO.setWeeks(weeks);
                    } catch (Exception e) {
                        // 如果解析失败，忽略weeks字段
                    }
                }

                timeSlotVOList.add(timeSlotVO);
            }

            CourseVO courseVO = CourseVO.builder()
                    .id(course.getId())
                    .name(course.getName())
                    .teacherName(user != null ? user.getName() : "未知教师")
                    .credit(course.getCredit())
                    .capacity(course.getCapacity())
                    .enrolledCount(course.getEnrolledCount())
                    .status(course.getStatus())
                    .timeSlots(timeSlotVOList)
                    .build();

            courseVOList.add(courseVO);
        }

        return ResultUtil.success(courseVOList);
    }

    @Override
    @Transactional
    public ResultUtil cancelCourse(String userId, String courseId) {
        // 1. 参数校验
        if (courseId == null || courseId.trim().isEmpty()) {
            return ResultUtil.error("课程ID不能为空");
        }

        // 2. 查询教师信息
        LambdaQueryWrapper<Teachers> teacherWrapper = new LambdaQueryWrapper<>();
        teacherWrapper.eq(Teachers::getUserId, userId);
        Teachers teacher = this.getOne(teacherWrapper);
        if (teacher == null) {
            return ResultUtil.error("教师信息不存在");
        }

        // 3. 查询课程
        Courses course = coursesMapper.selectById(courseId);
        if (course == null) {
            return ResultUtil.error(HttpStatus.NOT_FOUND, "课程不存在");
        }

        // 4. 验证课程是否属于该教师
        if (!course.getTeacherId().equals(teacher.getId())) {
            return ResultUtil.error("无权操作该课程");
        }

        // 5. 验证课程状态
        if (course.getStatus() != CourseStatus.approved) {
            return ResultUtil.error("只能取消已审核通过的课程");
        }

        // 6. 检查是否有学生选课
        LambdaQueryWrapper<Enrollments> enrollmentWrapper = new LambdaQueryWrapper<>();
        enrollmentWrapper.eq(Enrollments::getCourseId, courseId);
        long enrollmentCount = enrollmentsService.count(enrollmentWrapper);
        if (enrollmentCount > 0) {
            return ResultUtil.error("已有学生选课，无法取消");
        }

        // 7. 删除时间段
        LambdaQueryWrapper<TimeSlots> timeSlotWrapper = new LambdaQueryWrapper<>();
        timeSlotWrapper.eq(TimeSlots::getCourseId, courseId);
        timeSlotsService.remove(timeSlotWrapper);

        // 8. 删除课程
        int result = coursesMapper.deleteById(courseId);
        if (result <= 0) {
            return ResultUtil.error("取消失败");
        }

        return ResultUtil.success("课程已取消");
    }

    @Override
    public ResultUtil getCourseStudents(String userId, String courseId) {
        // 1. 参数校验
        if (courseId == null || courseId.trim().isEmpty()) {
            return ResultUtil.error("课程ID不能为空");
        }

        // 2. 查询教师信息
        LambdaQueryWrapper<Teachers> teacherWrapper = new LambdaQueryWrapper<>();
        teacherWrapper.eq(Teachers::getUserId, userId);
        Teachers teacher = this.getOne(teacherWrapper);
        if (teacher == null) {
            return ResultUtil.error("教师信息不存在");
        }

        // 3. 查询课程
        Courses course = coursesMapper.selectById(courseId);
        if (course == null) {
            return ResultUtil.error(HttpStatus.NOT_FOUND, "课程不存在");
        }

        // 4. 验证课程是否属于该教师
        if (!course.getTeacherId().equals(teacher.getId())) {
            return ResultUtil.error("无权查看该课程的学生");
        }

        // 5. 查询选课记录
        LambdaQueryWrapper<Enrollments> enrollmentWrapper = new LambdaQueryWrapper<>();
        enrollmentWrapper.eq(Enrollments::getCourseId, courseId);
        List<Enrollments> enrollments = enrollmentsService.list(enrollmentWrapper);

        // 6. 构建学生列表
        List<Map<String, Object>> studentList = new ArrayList<>();
        for (Enrollments enrollment : enrollments) {
            Students student = studentsMapper.selectById(enrollment.getStudentId());
            if (student == null) {
                continue;
            }

            Users user = usersService.getById(student.getUserId());
            if (user == null) {
                continue;
            }

            Map<String, Object> studentInfo = new HashMap<>();
            studentInfo.put("id", student.getId());
            studentInfo.put("studentNo", student.getStudentNo());
            studentInfo.put("name", user.getName());
            studentInfo.put("college", user.getCollege());
            studentInfo.put("major", student.getMajor());
            studentInfo.put("clazz", student.getClazz());
            studentList.add(studentInfo);
        }

        return ResultUtil.success(studentList);
    }
}
